      var todoMarkup;
      var extendedTodoMarkup;
      var iDAndDeadline;
      var projectJSON;

      $(function() {
        initProject('todoList.json');
        $('#filter').example('Search');
        setUsersName();
        $('#addProject').dialog({autoOpen: false, hide: "fadeOut", show: "blind",  draggable: true, modal: true, height: 130}, 'option', 'position', 'center');
      });

      function sortByTopic() {

      }

      function initProject(fileName) {
        iDAndDeadline  = new Object();
        projectJSON = fileName;
        renderTODOTable();
      }

      function clearProject() {
        $('#todoList').html('');
      }

      function changeProject(event) {
        clearProject();
        if ($(event.target).val() == "new") {
          addProject();
        }
        if ($(event.target).val().indexOf('.json') == -1) {
          return;
        }
        initProject($(event.target).val());
      }

      function addProject() {
        $('#addProject').dialog('open');
      }

      function addBeautyTips() {
        $.each($('.beautyTip'), function(index, beautyTip) {
          var position = new Array();
          if ($(beautyTip).hasClass('rightTip')) {
            position.push('right');
          }
          if ($(beautyTip).hasClass('leftTip')) {
            position.push('left');
          }
          $(beautyTip).bt({
            fill: '#CDE69C',
            cssStyles: {color: '#638421', fontWeight: 'bold'},
            shrinkToFit: true,
            padding: 10,
            cornerRadius: 10,
            spikeLength: 15,
            spikeGirth: 5,
            positions: position
          });
        });
      }

      function quickCreateProject(event) {
        if (event.keyCode == '13') {
          createProject();
        }
        else {
          return;
        }
      }

      function createProject() {
        $('#addProject').dialog('close');
        var newProject = $("#projectName").val().trim().toUpperCase();
        $('#projectSelection')[0].options[$('#projectSelection')[0].options.length - 1] = new Option(newProject, newProject);
        $('#projectSelection')[0].options[$('#projectSelection')[0].options.length] = new Option('-- ADD NEW --', 'new');
        $($('#projectSelection')[0]).val(newProject);
      }

      function cancelNewProject() {
        $('#addProject').dialog('close');
      }

      function setUsersName() {
        var cookieValue = $.url.decode(getCookie("myTodo"));
        if (cookieValue == null || cookieValue.indexOf("userName") == -1) {
          return;
        }
        cookieValue = cookieValue.substring(cookieValue.indexOf("{"));
        var user = new Object;
        user = $.parseJSON(cookieValue);
        $('.loggedInUser').html(user.name.toUpperCase() + " ");
      }


      function renderTODOTable() {
        var todoMarkup = $("#TODOTemplate").html();
        var extendedTodoMarkup = $("#TODOExtendedTemplate").html();
        <!--Compile markup strings as named templates-->
        $.template( "todoTemplate", todoMarkup );
        $.template( "todoExtendedTemplate", extendedTodoMarkup );
        $.getJSON(projectJSON, function(assignments){
          for(var task in assignments) {
            iDAndDeadline[assignments[task].id] = assignments[task].deadline;
            $.tmpl("todoTemplate", assignments[task]).appendTo("#todoList");
            $.tmpl("todoExtendedTemplate", assignments[task]).appendTo("#todoList").hide();
            $('#' + assignments[task].id + '_extended').find('.stateSelection').val(assignments[task].status);
          }
        }).success(function() {
            postRender();
          });
      }

      function postRender() {
        addBeautyTips();
        convertPrioritiesToImage();
        generatePriorityPickers();
        generateTags();
        populateTODOCounts();
        bindStatusHandlers();
        $.each($('.tagHolder'), function(index, value){
          $($('.tagHolder')[index]).tagsInput()
        });
      }

      function bindStatusHandlers() {
        $.each($('.START'), function(index, startButton) {
          $(startButton).click(function() {startTask(startButton);});
        });
        $.each($('.FINISH'), function(index, startButton) {
          $(startButton).click(function() {finishTask(startButton);});
        });
      }

      function restartTask(button) {
        $(button).removeClass('DONE').removeClass('FINISH').addClass('START');
        $(button).val('START');
        $(button).click(function() {startTask(button)});
      }

      function startTask(button) {
        $(button).removeClass('START').removeClass('DONE').addClass('FINISH');
        $(button).val('FINISH');
        $(button).click(function() {finishTask(button)});
      }

      function finishTask(button) {
        $(button).removeClass('FINISH').removeClass('START').addClass('DONE');
        $(button).val('DONE');
      }

      function populateTODOCounts() {
        var TODOsToday = 0;
        var TODOsArchived = 0;
        var TODOsThisWeek = 0;
        var today = new Date();
        var day = (today.getDate().length == 1 ? ("0" + today.getDate()) : today.getDate());
        var month = ((today.getMonth() + 1 + "").length == 1 ? ("0" + (today.getMonth() + 1)) : (today.getMonth() + 1));
        var todayFormatted = day + "/" + month + "/" + today.getFullYear();
        $.each(iDAndDeadline, function(index, deadLine){
          if(deadLine == todayFormatted){
            TODOsToday ++;
          }
        });
        $('#TODOsToday').html(TODOsToday);
      }

      function addNew() {
        var id = new Date().getTime();
        var assignment = new Object();
        assignment['id'] = "" + id;
        assignment['status'] = "START";
        assignment['priority'] = '1';
        $.tmpl("todoExtendedTemplate", assignment).prependTo("#todoList").hide();
        $.tmpl("todoTemplate", assignment).prependTo("#todoList");
        $("#" + id).find(".id").click();
        convertPriorityToImage({"value" : $("#" + id).find(".collapsed-priority")});
        generatePriorityPicker($("#" + id + "_extended").find('.priorityPicker')[0]);
        $($('.tagHolder')[0]).tagsInput();
        var startButton = $("#" + id).find('.START');
        $(startButton).click(function() {startTask(startButton)});
      }

      function convertPrioritiesToImage() {
        $.each($('.collapsed-priority'), function(index, value) {
          convertPriorityToImage({"value" : value});
        });
      }

      function convertPriorityToImage(event) {
        var barHolder = $(event.value).find('.bars');
        var bars = parseInt($(event.value).find('.priorityNumber').val());
        barHolder.html('');
        for (var i = 1; i <= bars; i++) {
          $($(event.value).find('.bars').append("<img class='" + i + "'src='images/bar.png'/> "));
        }
      }

      function generatePriorityPickers() {
        var priorityContainers = $('.priorityPicker');
        $.each(priorityContainers, function(index, value) {
          generatePriorityPicker(value);
        });
      }

      function generatePriorityPicker(value) {
        var bars = parseInt($(value).find('.priorityNumber').val());
        for (var i = 1; i <= bars; i++) {
          $(value).find('.bars').append("<img class='" + i + "'src='images/bar.png' onmouseover='highlightPreviousBars(event)' onmouseout='restoreBars(event)' onclick='setBars(event)'/> ");
        }
        for (var i = bars + 1; i <= 5; i++) {
          $(value).find('.bars').append("<img class='" + i + "'src='images/bar-light.png' onmouseover='highlightPreviousBars(event)' onmouseout='restoreBars(event)' onclick='setBars(event)'/> ");
        }
      }

      function generateTags() {
        $.each($('.tags'), function(index, tagCSVHolder) {
          formatTags(tagCSVHolder);
        });
      }

      function formatTags(tagCSVHolder) {
        var tags = $(tagCSVHolder).html().split(",");
        $(tagCSVHolder).html('');
        if(tags.length < 1 || (tags.length == 1 && tags[0] == '')){
          return
        }
        $.each(tags, function(index, tag) {
          $(tagCSVHolder).append("<span class='tags-topic'>" + tag + "</span>");
        });
      }

      function highlightPreviousBars(event) {
        var targetBar = $(event.target);
        var barNumber = parseInt(targetBar.attr("class"));
        var barHolder = targetBar.parent();
        for (var i = 1; i <= barNumber; i++) {
          barHolder.find('.' + i).attr("src", "images/bar.png");
        }
        for (var i = barNumber + 1; i <= 5; i++) {
          barHolder.find('.' + i).attr("src", "images/bar-light.png");;
        }
      }

      function restoreBars(event) {
        var targetBar = $(event.target);
        var barHolder = targetBar.parent();
        var bars = barHolder.parent().find('.priorityNumber').val();
        for (var i = 1; i <= 5; i++) {
          barHolder.find('.' + i).attr("src", "images/bar-light.png");
        }
        for (var i = 1; i <= bars; i++) {
          barHolder.find('.' + i).attr("src", "images/bar.png");
        };
      }

      function setBars(event) {
        var clickedBar = $(event.target);
        clickedBar.parent().parent().find('.priorityNumber').val(clickedBar.attr("class"));
      }

      function expandTODO(id) {
        $("#" + id).hide();
        $("#" + id + "_extended").show();
        $("#" + id + "_deadline").datepicker({constrainInput: false, minDate: new Date});
        $('#' + id + "_extended").find('.stateSelection').val($('#' + id).find('.statusButton').val());
      }

      function unExpandTODO(id) {
        $("#" + id + "_extended").hide();
        $("#" + id).show();
      }

      function unExpandAndSaveTODO(id) {
        var extendedRow = $("#" + id + "_extended");
        if (extendedRow.find(".topic").val().trim() == '') {
          $('#todoTable').find(extendedRow).remove();
          $('#todoTable').find($('#' + id)).remove();
          idAndDeadline[id] = ''
          return;
        }
        unExpandTODO(id);
        var newTopic = extendedRow.find(".topic").val();
        var newState = extendedRow.find('.stateSelection').val();
        if (newState == 'DONE') {
          finishTask($("#" + id).find('.statusButton'));
        }
        if (newState == 'FINISH') {
          startTask($("#" + id).find('.statusButton'));
        }
        if (newState == 'START') {
          restartTask($("#" + id).find('.statusButton'));
        }
        var newDeadline = extendedRow.find("#" + id + "_deadline").val();
        var newPriority = extendedRow.find(".priorityNumber").val();
        var newTags = extendedRow.find(".tagHolder").val();
        var collapsedRow = $("#" + id);
        collapsedRow.find(".topic").html(newTopic);
        collapsedRow.find(".deadline").html(newDeadline);
        collapsedRow.find(".priorityNumber").val(newPriority);
        collapsedRow.find(".tags").html(newTags);
        formatTags(collapsedRow.find(".tags"));
        convertPriorityToImage({"value" : $("#" + id).find(".collapsed-priority")});
        convertPriorityToImage({"value" : $("#" + id).find(".collapsed-priority")});
        iDAndDeadline[id] = newDeadline;
        populateTODOCounts();
      }

      function deleteTODO(target) {
        <!--TODO: SEND delete message with target id to server-->
        iDAndDeadline[target] = '';
        $('#' + target).remove();
        $('#' + target + "_extended").remove();
        populateTODOCounts();
      }

      function quickSearch(e) {
        if(e.keyCode == 13) {
          search();
        }
        else {
          return false;
        }
      }

      function search() {
        var defaultValue = "search";
        var filter = $('#filter').val().toLowerCase().trim();
        if (filter == defaultValue) {
          filter = '';
        }
        var filteredIds = [];
        var fieldsToSearchFrom = ['id', 'topic', 'deadline', 'comment', 'tags', 'status'];
        if (filter.indexOf(":") != -1) {
          fieldsToSearchFrom = getAdvancedSearchField(fieldsToSearchFrom, filter);
          filter = filter.substr(filter.indexOf(":") + 1).trim();
        }
        $.getJSON(projectJSON, function(assignments){
          for(var task in assignments) {
            var assignment = assignments[task];
            $.each(fieldsToSearchFrom, function(index, parameterName){
              if ((assignment[parameterName]).toLowerCase().indexOf(filter) != -1) {
                filteredIds.push(assignment['id']);
              }
            })
          }
        }).success(function() {showFilteredTODOs(filteredIds);});

      }

      function getAdvancedSearchField(allFields, filter) {
        var searchFields = [];
        $.each(allFields, function(index, field) {
          if(filter.indexOf(field + ":") != -1 || filter.indexOf(field + " :") != -1) {
            searchFields.push(field);
          }
        });
        return (searchFields.length == 1) ? searchFields : allFields;
      }

      function showFilteredTODOs(filteredIds) {
        hideAllTODOs();
        $.each(filteredIds, function(index, id) {
          $("#" + id).show();
        })
      }

      function hideAllTODOs() {
        $.each($('.extended-TODO'), function(index, value) {
          $($('.collapsed-TODO')[index]).hide();
        })
        $.each($('.extended-TODO'), function(index, value) {
          $($('.extended-TODO')[index]).hide();
        })
      }

      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-30653074-1']);
      _gaq.push(['_trackPageview']);

      (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();